﻿using UnityEngine;
using System.Collections;

namespace UEngine
{
    public class InitLoadingWin : IWindow
    {
        private GameObject   m_winGo = null;
        private EWindowsName m_name  = EWindowsName.INITLOADING;

        public void OnPreLoad()
        {
            Debug.Log("Regist INITLOADING_CREATE");
            Debug.Log("Regist INITLOADING_CLOSE");
            EventManager.Instance().Registe(EEventName.INITLOADING_CREATE, OnWinEvent);
            EventManager.Instance().Registe(EEventName.INITLOADING_CLOSE, OnWinEvent);
        }

        public void OnCreate()
        {
            if (m_winGo == null)
            {
                m_winGo = WindowsManager.Instance().GetWinGo(m_name); 
            }

            if (m_winGo == null)
            {
                m_winGo = GameObject.Instantiate(Resources.Load("UI/Image_Loading", typeof(GameObject))) as GameObject;
            }

            if (m_winGo == null)
            {
                DebugHelper.ErrorMessage("loadingGo == null");
            }

            InitLoadingCom initLoadingCom = m_winGo.GetComponent<InitLoadingCom>();
            if (initLoadingCom == null)
            {
                initLoadingCom = m_winGo.AddComponent<InitLoadingCom>();
            }
            m_winGo.SetActive(true);
            WindowsManager.Instance().AddWinToRoot(m_name, m_winGo);
            //WindowsManager.Instance().AddUI(m_winGo);
        }

        public void OnClose()
        {
            if (m_winGo == null)
            {
                DebugHelper.ErrorMessage("m_winGo == null");
                return;
            }

            //防止脚本中带协程代码，重新激活后不执行
            InitLoadingCom initLoadingCom = m_winGo.GetComponent<InitLoadingCom>();
            if (initLoadingCom != null)
            {
                GameObject.Destroy(initLoadingCom);
            }
            m_winGo.SetActive(false);
            WindowsManager.Instance().RemoveWin(m_name);
        }

        public void OnWinEvent(object sender, SHEventArgs eArgs)
        {
            switch (eArgs.m_EventName)
            {
                case EEventName.INITLOADING_CREATE:
                    Debug.Log("OnWinEvent INITLOADING_CREATE");
                    OnCreate();
                    break;
                case EEventName.INITLOADING_CLOSE:
                    OnClose();
                    break;
            }
        }
    }
}

